<?php
/**
 * User: wyqiang <2925528279@qq.com>
 * Date: 16-10-10 下午8:05
 */

// 获取当前用户的OpenId
function get_openid($openid = NULL) {
    $token = get_token ();
    if ($openid !== NULL) {
        session ( 'openid_' . $token, $openid );
    } elseif (! empty ( $_REQUEST ['openid'] )) {
        session ( 'openid_' . $token, $_REQUEST ['openid'] );
    }
    $openid = session ( 'openid_' . $token );

    $isWeixinBrowser = isWeixinBrowser ();
    if (empty ( $openid ) && $isWeixinBrowser) {
        $callback = GetCurUrl ();
        OAuthWeixin ( $callback );
    }

    if (empty ( $openid )) {
        return - 1;
    }

    return $openid;
}

// 获取当前用户的Token
function get_token($token = NULL) {
    if ($token !== NULL) {
        session ( 'token', $token );
    } elseif (! empty ( $_REQUEST ['token'] )) {
        session ( 'token', $_REQUEST ['token'] );
    }
    $token = session ( 'token' );

    if (empty ( $token )) {
        return - 1;
    }

    return $token;
}

// php获取当前访问的完整url地址
function GetCurUrl() {
    $url = 'http://';
    if (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] == 'on') {
        $url = 'https://';
    }
    if ($_SERVER ['SERVER_PORT'] != '80') {
        $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
    } else {
        $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    }
    // 兼容后面的参数组装
    if (stripos ( $url, '?' ) === false) {
        $url .= '?t=' . time ();
    }

    return $url;
}

// 判断是否是在微信浏览器里
function isWeixinBrowser() {
    $agent = $_SERVER ['HTTP_USER_AGENT'];
    if (! strpos ( $agent, "icroMessenger" )) {
        return false;
    }
    return true;
}

function OAuthWeixin($callback) {
    $isWeixinBrowser = isWeixinBrowser ();
    $info = get_token_appinfo ();
    if (! $isWeixinBrowser || $info ['type'] != 2 || empty ( $info ['appid'] )) {
        redirect ( $callback . '&openid=-1' );
    }
    $param ['appid'] = $info ['appid'];

    if (! isset ( $_GET ['getOpenId'] )) {
        $param ['redirect_uri'] = $callback . '&getOpenId=1';
        $param ['response_type'] = 'code';
        $param ['scope'] = 'snsapi_base';
        $param ['state'] = 123;
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';
        redirect ( $url );
    } elseif ($_GET ['state']) {
        $param ['secret'] = $info ['secret'];
        $param ['code'] = I ( 'code' );
        $param ['grant_type'] = 'authorization_code';

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query ( $param );
        $content = file_get_contents ( $url );
        $content = json_decode ( $content, true );
        redirect ( $callback . '&openid=' . $content ['openid'] );
    }
}

// 获取公众号的信息
function get_token_appinfo($token = '') {
    empty ( $token ) && $token = get_token ();
    $map = [ 'token' => $token ];
    $info = M ( 'member_public' )->where ( $map )->find ();
    return $info;
}

/**
 * 获取微信web链接token
 * @param array $param
 * @return string
 */
function encodeWxWebToken($param, $isTimer = true) {
    $arr = array ();
    if ($param) {

        foreach ( $param as $k => $v ) {
            array_push ( $arr, $k . '=' . $v );
        }
    }
    if ($isTimer) {
        $arr [] = 'time=' . time ();
    }
    $arr [] = 'sig=' . genWxWebTokenSig_ ( implode ( ';', $arr ) );
    $str = implode ( ';', $arr );
    return base64_encode ( $str );
}

/**
 * 生成签名
 * @param string $str
 * @return string
 */
function genWxWebTokenSig_($str) {
    return md5 ( $str . C("WX_WEB_TOKEN_KEY") );
}

/**
 * 发送短信验证码
 * @param $mobileNum
 * @param $msg
 * @return bool
 */
function send_sms($mobile, $msg){
    $url='http://sms.106jiekou.com/utf8/sms.aspx';
    $paramArr = array(
        'account'   => '534217239',
        'password'  => 'liu1104liu',
        'mobile'    => $mobile,
        'content'   => rawurlencode($msg),
    );
    $post_param = http_build_query($paramArr);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,$url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT, 5);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_param);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_NOBODY, false);
    $state_code = curl_exec($curl);
    curl_close($curl);

    if($state_code == 100){
        return true;
    }else{
        return false;
    }
}

// 获取当前用户的OpenId
function getOpenid($appinfo) {
    if(!$appinfo || empty ( $appinfo ['app_id'] )) return -1;

    $isWeixinBrowser = isWeixinBrowser ();
    if (empty ( $openid ) && $isWeixinBrowser) {
        $callback = GetCurUrl ();
        OAuthWeixinAppinfo ( $callback, $appinfo );
    }

    if (empty ( $openid )) {
        return - 1;
    }

    return $openid;
}
//根据公众号信息获取用户Openid
function OAuthWeixinAppinfo($callback, $info) {
    $isWeixinBrowser = isWeixinBrowser ();
    if (! $isWeixinBrowser || $info ['type'] != 2 || empty ( $info ['app_id'] )) {
        redirect ( $callback . '&openid=-1' );
    }
    $param ['appid'] = $info ['app_id'];

    if ( !isset ( $_GET ['getOpenId'] )) {
        $param ['redirect_uri'] = $callback . '&getOpenId=1';
        $param ['response_type'] = 'code';
        //$param ['scope'] = 'snsapi_base';//基础接口，不能用来获取用户信息
        $param ['scope'] = 'snsapi_userinfo';//
        $param ['state'] = 123;
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';

        redirect ( $url );
    } elseif ($_GET ['state']) {
        $param ['secret'] = $info ['app_secret'];
        $param ['code'] = I ( 'code' );
        $param ['grant_type'] = 'authorization_code';

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query ( $param );
        $content = file_get_contents ( $url );
        $content = json_decode ( $content, true );

        redirect ( $callback . '&openid=' . $content ['openid'] . '&access_token=' . $content ['access_token']);
    }
}

/**
 * 生成消息唯一ID
 * @param $message
 * @return string
 */
function createMessageId($message){
    if ($message && $message->message_id) {
        return $message->message_id;
    }
    if ($message) {
        $id = md5($message->from_user.$message->created_at);
        return substr($id, 8, 18);
    }
    return uniqid();
}

if (!function_exists('curl_get')){
    /**
     * curl get请求
     * @param $apiUrl
     * @param int $timeout
     * @return mixed
     */
    function curl_get($apiUrl, $timeout = 30){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $apiUrl);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
        curl_setopt($curl, CURLOPT_POST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response,true);

        return $response;
    }
}

/**
 * 格式化秒为日时分
 * @param $second
 * @return string
 */
function formatSecond($second){
    $dateline = '';
    if($second >= 86400){
        $day = floor($second / 86400);
        $second = $second - $day * 86400;

        $dateline .= $day . '天';
    }

    if($second >= 3600){
        $hour = floor($second / 3600);
        $second = $second - $hour * 3600;

        $dateline .= $hour . '小时';
    }

    if($second >= 60){
        $minute = floor($second / 60);
        //$second = $second - $minute * 60;

        $dateline .= $minute . '分钟';
    }

    return $dateline ? $dateline : '0小时0分钟';
}

/**
 * 检查用户是否移动端登录
 * @return bool
 */
function is_m_login(){
    $uid = session('user_id');
    if ($uid) {
        return true;
    } else {
        return false;
    }
}
/*
 * 获取用户角色
 */
if(!function_exists('user_role')){
    function user_role($role = null){
        if(!is_null($role)){
            session('user_role', $role);
        }else{
            $user_role = session('user_role');
            return  ($user_role) ? $user_role : '';
        }
    }
}
